import { createRouter, createWebHistory } from "vue-router"
import nProgress from "nprogress"
import "nprogress/nprogress.css"
import storage from "@/utils/storage"
import { getRouters } from "@/api/permission"
import { usePermissionStore } from "@/stores/permission"
import { createRouter as ucreateRouter, createRoute } from "@/utils/permission"
// import allroutes from "./routers"
let allroutes = [] as any
let inited = false
const routes = [
  {
    path: "/:404(.*)*",
    component: () => import("../components/othersPage/errorPage.vue"),
    meta: {
      name: "404",
    },
  },
  {
    path: "/",
    name: "login",
    component: () => import("../components/loginView.vue"),
    meta: {
      name: "登录",
    },
  },
  {
    path: "/layout",
    name: "layout",
    redirect: "/home",
    component: () => import("../components/layout/AppLayout.vue"),
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("@/components/homeView.vue"),
        children: [],
        meta: {
          name: "首页",
        },
      },
    ],
  },
]

// 权限

const router = createRouter({
  history: createWebHistory("/user"),
  routes,
})
nProgress.configure({
  showSpinner: true,
})
const pathWhite = ["/"]
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  nProgress.start()
  const permissionStore = usePermissionStore()
  if (!pathWhite.includes(to.path)) {
    if (!storage.get("token")) {
      next({ name: "login", query: { redirect: to.path } })
      return
    }
  }
  if (!inited) {
    try {
      const roles = await getRouters("/bem/routertest")
      if (roles.code == 200) {
        allroutes = createRoute(storage.get("allRoute"))
        storage.set("roles", roles.data.routers)
        permissionStore.setPermission(roles.data.routers)
        const res = ucreateRouter(allroutes, roles.data.routers)

        
        storage.set("routes", res)
        permissionStore.setCrouter(res)
        res.forEach((r) => {
          router.addRoute("layout", r)
          console.log(router.getRoutes(),'router')
        })
   
        next({ ...to, replace: true })
        inited = true
        return
      }
    } catch (error) {
      console.log(error,'error')
      console.log("routererror 重新通过新token获取数据中")
    }
  } else {
    inited = false
    next()
    return
  }
  next()
})

// 全局后置钩子
router.afterEach(() => {
  nProgress.done(true)
})

export { router, allroutes }
